package com.gzs.learn.springcloud.controller;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.gzs.learn.springcloud.clients.ISerialQueryClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.common.collect.Sets;
import com.gzs.learn.springcloud.dto.UserDto;
import com.gzs.learn.springcloud.entity.User;
import com.gzs.learn.springcloud.service.IUserService;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final ISerialQueryClient serialQueryClient;
    private final IUserService userService;

    @PostMapping(value = "{userIds}")
    public List<User> getUserByIds(@PathVariable("userIds") String userIds) {
        List<Long> userIdList = Stream.of(userIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(userIdList)) {
            throw new IllegalArgumentException(String.format("userids can not be null"));
        }
        Set<Long> userIdSets = Sets.newHashSet(userIdList);
        return userService.findAllByIds(userIdSets);
    }

    @GetMapping(value = "/{userId}")
    public UserDto getUserById(@PathVariable("userId") Long userId) {
        Optional<UserDto> userDto = userService.findByUserId(userId);
        return userDto.get();
    }

    @GetMapping(value = "/{userId}/addr/{addressId}")
    public UserDto getUserByIdAndAddressId(@PathVariable("userId") Long userId,
                                           @PathVariable("addressId") Long addressId) {
        Optional<UserDto> userDto = userService.findByUserAndAddress(userId, addressId);
        return userDto.get();
    }

    @GetMapping(value = "member-serial")
    public Long memberSerial() {
        log.info("get member serial");
        return serialQueryClient.getSegmentId("member").getData();
    }

}
